package com.ad.pet.utils;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ad.pet.App;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.constant.Constant;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;

/**
 * 常用的key
 * Created by dongliangshi on 2016/11/10.
 */

public class LyxUtils {
    private LyxUtils() {
    }

    //签名算法
    public static String getSign(HashMap<String, String> map) {
        ArrayList<String> allKey = new ArrayList<>();

        for (String key : map.keySet()) {
            allKey.add(key);
        }

        Collections.sort(allKey);

        StringBuffer sb = new StringBuffer("");
        for (String key : allKey) {
            if (!Constant.SIGN.equals(key) && (!Constant.ACCESS_TOKEN.equals(key)) && (!Constant.LANG.equals(key)) && !Constant.CURRENCY.equals(key) && !Constant.CHOSE_COUNTRY.equals(key) && !Constant.IMAGE.equals(key)) {
                sb.append(key).append("=").append(LyxUtils.encodeString(map.get(key))).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        Logger.e("sb_strig:" + sb.toString());
        return md5(sb.toString(), "e828854e53b93a3b1e19c4cab2de707a");
    }

    public static String md5(String string, String slat) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest((string + slat).getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String byte2String(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            int a = b[i];
            if (a < 0)
                a += 256;
            if (a < 16)
                sb.append("0");
            sb.append(Integer.toHexString(a));

        }
        return sb.toString();
    }

    public static String getVersionName() {
        PackageManager pm = App.getApp().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(App.getApp().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return pi.versionName;
    }

    //拿到屏幕宽度
    public static int getWinWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int getWinHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5);
    }

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) ((dp - 0.5) * scale);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    //string
    public static String getString(int stringId) {
        return App.getApp().getString(stringId);
    }

    //color
    public static int getColor(int colorId) {
        int color = App.getApp().getResources().getColor(colorId);
        return color;
    }


    // IMEI码
    private static String getIMIEStatus(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "0";
        }
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    // Mac地址
    public static String getLocalMac(Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /*
    * 获取到客户ID，即IMSI(用于识别移动用户所归属的移动通信网；MSIN是移动用户识别码，用以识别某一移动通信网中的移动用户)
    *
            * @return
            */
    public static String getIMSI(Context mContext) {
        TelephonyManager telephonyManager = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "0";
        }
        return telephonyManager.getSubscriberId();
    }

    /**
     * 获取设备id  获取手机的IMEI号码(是移动设备国际身份码的缩写，移动设备国际辨识码，是由15位数字组成的"电子串号"，它与每台手机一一对应，
     * 而且该码是全世界唯一的)
     *
     * @return
     */
    public static String getIMEI(Context mContext) {
        String imei = "";

        TelephonyManager telephonyManager = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "0";
        }
        imei = telephonyManager.getDeviceId();
        return imei;
    }

    public static int dip2px1(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static void reflex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = LyxUtils.dip2px1(tabLayout.getContext(), 10);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 获取Application下面的metaData
     *
     * @return
     * @author SHANHY
     * @date 2015年12月30日
     */
    public static String getAppMetaData(String meta_name, Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(App.getApp().getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(meta_name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String encodeString(String s) {
        try {

            return URLEncoder.encode(s, "utf-8");


        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }

    /**
     * 取小数两位
     *
     * @param d
     * @return
     */
    public static double formatDouble2(double d) {
        BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bg.doubleValue();
    }

    /**
     * 取小数两位
     *
     * @param d
     * @return
     */
    public static double formatDoubleRate(double d) {
        BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_UP);
        return bg.doubleValue();
    }

    /**
     * 乘法
     *
     * @param d
     * @return
     */
    public static double formatMultiply(double d, double d2) {
        BigDecimal bg = new BigDecimal(d);
        BigDecimal bg1 = new BigDecimal(d2);
        return LyxUtils.formatDouble2(bg.multiply(bg1).doubleValue());
    }

    /**
     * 加法
     *
     * @param d
     * @return
     */
    public static double formatAdd(double d, double d2) {
        BigDecimal bg = new BigDecimal(d);
        BigDecimal bg1 = new BigDecimal(d2);
        return LyxUtils.formatDouble2(bg.add(bg1).doubleValue());
    }

    /**
     * 减法
     *
     * @param d
     * @return
     */
    public static double formatSubtract(double d, double d2) {
        BigDecimal bg = new BigDecimal(d);
        BigDecimal bg1 = new BigDecimal(d2);
        return LyxUtils.formatDouble2(bg.subtract(bg1).doubleValue());
    }

    /**
     * 除法
     *
     * @param d
     * @return
     */
    public static double formatDivide(double d, double d2) {
        BigDecimal bg = new BigDecimal(d);
        BigDecimal bg1 = new BigDecimal(d2);
        return bg.divide(bg1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    public static String getImgUrl(int drawable) {
        String uril = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + App.getApp().getResources().getResourcePackageName(drawable) + "/"
                + App.getApp().getResources().getResourceTypeName(drawable) + "/"
                + App.getApp().getResources().getResourceEntryName(drawable)).toString();
        return uril;
    }


    /***
     * 获取文件的string
     * @return
     */
    public static String getFileString(File xmlfile) {
        String xmlString;
        byte[] strBuffer = null;
        int flen = 0;
        try {
            InputStream in = new FileInputStream(xmlfile);
            flen = (int) xmlfile.length();
            strBuffer = new byte[flen];
            in.read(strBuffer, 0, flen);
        } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        xmlString = new String(strBuffer); //构建String时，可用byte[]类型，

        return xmlString;
    }


    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 返回系统使用的是哪一种语言！
     */
    public static String isSystemLanguageEnglish(Context context) {
        Resources resource = context.getResources();
        Configuration config = resource.getConfiguration();
        Logger.e("当前系统语言是--->：" + config.locale.getLanguage());
        String language = "";
        switch (config.locale.getLanguage()) {
            case "en":
                language = "en";
                break;
            case "fr":
                language = "fr";
                break;
            case "pt":
                language = "pt";
                break;

            case  "zh":
                language = "cn";
                break;
            default:
                language = "en";
                break;
        }
        return language;
    }

    /**
     * 设置语言
     *
     * @param context
     */
    public static void changeAppLanguage(Context context, String kkk) {
        //这是SharedPreferences工具类，用于保存设置，代码很简单，自己实现吧
        // 获得res资源对象
        Resources resources = context.getResources();
        // 获得设置对象
        Configuration config = resources.getConfiguration();
        // 获得屏幕参数：主要是分辨率，像素等。
        DisplayMetrics dm = resources.getDisplayMetrics();
        config.locale = Locale.CHINA;
        switch (kkk) {
            case "en":
                config.locale = Locale.ENGLISH;
                break;
            case "fr":
                config.locale = Locale.FRANCE;
                break;
            case "pt":
                config.locale = new Locale("pt");
                break;
            case  "cn":
                config.locale= Locale.CHINESE;
                break;

            default:
                config.locale = Locale.ENGLISH;
                break;
        }


        resources.updateConfiguration(config, dm);

    }


    public static void showFABAnimation(View view) {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f);
        PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f);
        ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ).setDuration(400).start();
    }

    /**
     * by moos on 2017.8.21 * func:隐藏fab的动画
     */
    public static void hideFABAnimation(View view) {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 0f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 0f);
        PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 0f);
        ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ).setDuration(400).start();
    }

    /**
     * 用于传url拼接语言包文件夹
     * @param urlActiion
     * @return
     */
    public static String muchLuanguageUrl(String urlActiion){
        StringBuffer buffer = new StringBuffer();
        buffer.append(getString(R.string.ip_default));
        if (TextUtils.equals("cn", SpUtil.getInstance().getString(Constant.LANGUAGE))){
            buffer.append(urlActiion);
        }else {
            buffer.append("/");
            buffer.append(SpUtil.getInstance().getString(Constant.LANGUAGE));
            buffer.append(urlActiion);
        }
        return buffer.toString();
    }

    public static String imageToBase64(File path){
        if(path==null){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

}
